package com.mxp.elm.service;

import com.mxp.elm.entity.UserEntity;
import com.mxp.elm.entity.LoginVo;
import com.mxp.elm.mapper.UserMapper;
import com.mxp.elm.utils.MD5Utils;
import com.mxp.elm.utils.PageUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author mxp
 * @date 2023/2/23 11:27
 */
@Service
public class UserService {

    @Resource
    private UserMapper userMapper;

    public int doSave(UserEntity userEntity) {
        userEntity.setUserPwd("123456");
        return userMapper.save(userEntity);
    }

    public PageUtil queryPage(PageUtil pageUtil) {
        int start = (pageUtil.getCurPage() - 1) * pageUtil.getLimit();
        List<UserEntity> page = userMapper.queryPage(pageUtil, start);
        pageUtil.setData(page);
        pageUtil.setSearchName(null);
        pageUtil.setTotalPage(userMapper.count());
        return pageUtil;
    }

    public UserEntity getUserById(Integer id) {
        return userMapper.getUserById(id);
    }

    public UserEntity verifyUser(LoginVo vo) {
        UserEntity user = userMapper.getUserByNameOrEmailAndPwd(vo.getLoginName());
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        if (!user.getUserPwd().equals(MD5Utils.code(vo.getLoginPwd()))) {
            throw new RuntimeException("用户名或密码错误！");
        }

        if (user.getUserStatus().equals((byte) 0)) {
            throw new RuntimeException("当前用户暂时无法登陆，请联系管理员！");
        }
        return user;
    }

    public Integer updateUserById(UserEntity user) {
        return userMapper.updateUserById(user);
    }

    public Integer modifyUserStatusById(Integer id) {
        return userMapper.modifyStatusById(id);
    }

    public Integer register(UserEntity user) {
        return userMapper.insertUser(user);
    }

    public Integer resetPwd(UserEntity user) {
        return userMapper.resetPwd(user);
    }
}
